package org.jeecg.modules.gcProject.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.exOperationRecord.service.IExOperationRecordService;
import org.jeecg.modules.gcProject.entity.GcProjectAttachment;
import org.jeecg.modules.gcProject.service.IGcProjectAttachmentService;
import org.jeecg.modules.gcProject.vo.GcProjectAuditParam;
import org.jeecg.modules.gcProject.vo.StatusEnum;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.gcProject.entity.GcProjectEntrySection;
import org.jeecg.modules.gcProject.entity.GcProjectEntry;
import org.jeecg.modules.gcProject.vo.GcProjectEntryPage;
import org.jeecg.modules.gcProject.service.IGcProjectEntryService;
import org.jeecg.modules.gcProject.service.IGcProjectEntrySectionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 项目进场
 * @Author: jeecg-boot
 * @Date:   2024-08-11
 * @Version: V1.0
 */
@Api(tags="项目进场")
@RestController
@RequestMapping("/gcProject/gcProjectEntry")
@Slf4j
public class GcProjectEntryController {
	@Autowired
	private IGcProjectEntryService gcProjectEntryService;
	@Autowired
	private IGcProjectEntrySectionService gcProjectEntrySectionService;
	@Autowired
	private IGcProjectAttachmentService gcProjectAttachmentService;
	 @Autowired
	 private ISysCategoryService sysCategoryService;
	/**
	 * 分页列表查询
	 *
	 * @param gcProjectEntry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "项目进场-分页列表查询")
	@ApiOperation(value="项目进场-分页列表查询", notes="项目进场-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<GcProjectEntry>> queryPageList(GcProjectEntry gcProjectEntry,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GcProjectEntry> queryWrapper = QueryGenerator.initQueryWrapper(gcProjectEntry, req.getParameterMap());
		Page<GcProjectEntry> page = new Page<GcProjectEntry>(pageNo, pageSize);
		IPage<GcProjectEntry> pageList = gcProjectEntryService.page(page, queryWrapper);
		// 遍历查询结果，设置行业分类展示字段
		for (GcProjectEntry section : pageList.getRecords()) {
			SysCategory sysCategory = sysCategoryService.getById(section.getXmhyfl());
			if (sysCategory != null) {
				section.setIndustryType(sysCategory.getName());
			}
		}
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param gcProjectEntryPage
	 * @return
	 */
	@AutoLog(value = "项目进场-添加")
	@ApiOperation(value="项目进场-添加", notes="项目进场-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody GcProjectEntryPage gcProjectEntryPage) {
		GcProjectEntry gcProjectEntry = new GcProjectEntry();
		BeanUtils.copyProperties(gcProjectEntryPage, gcProjectEntry);
		gcProjectEntry.setEntryStatus(StatusEnum.SAVE.getCode());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		gcProjectEntry.setSysPlatformCode(sysUser.getPlatformCode());
		gcProjectEntryService.saveMain(gcProjectEntry, gcProjectEntryPage.getGcProjectEntrySectionList(),gcProjectEntryPage.getGcProjectAttachmentList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param gcProjectEntryPage
	 * @return
	 */
	@AutoLog(value = "项目进场-编辑")
	@ApiOperation(value="项目进场-编辑", notes="项目进场-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody GcProjectEntryPage gcProjectEntryPage) {
		GcProjectEntry gcProjectEntry = new GcProjectEntry();
		BeanUtils.copyProperties(gcProjectEntryPage, gcProjectEntry);
		GcProjectEntry gcProjectEntryEntity = gcProjectEntryService.getById(gcProjectEntry.getId());
		if(gcProjectEntryEntity==null) {
			return Result.error("未找到对应数据");
		}
		gcProjectEntryService.updateMain(gcProjectEntry, gcProjectEntryPage.getGcProjectEntrySectionList(),gcProjectEntryPage.getGcProjectAttachmentList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目进场-通过id删除")
	@ApiOperation(value="项目进场-通过id删除", notes="项目进场-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		gcProjectEntryService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目进场-批量删除")
	@ApiOperation(value="项目进场-批量删除", notes="项目进场-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.gcProjectEntryService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目进场-通过id查询")
	@ApiOperation(value="项目进场-通过id查询", notes="项目进场-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<GcProjectEntry> queryById(@RequestParam(name="id",required=true) String id) {
		GcProjectEntry gcProjectEntry = gcProjectEntryService.getById(id);
		if(gcProjectEntry==null) {
			return Result.error("未找到对应数据");
		}
		SysCategory sysCategory=new SysCategory();
		sysCategory=sysCategoryService.getById(gcProjectEntry.getXmhyfl());//获取这个树节点对象
		gcProjectEntry.setIndustryType(sysCategory.getName());
		return Result.OK(gcProjectEntry);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目标段信息通过主表ID查询")
	@ApiOperation(value="项目标段信息主表ID查询", notes="项目标段信息-通主表ID查询")
	@GetMapping(value = "/queryGcProjectEntrySectionByMainId")
	public Result<List<GcProjectEntrySection>> queryGcProjectEntrySectionListByMainId(@RequestParam(name="id",required=true) String id) {
		List<GcProjectEntrySection> gcProjectEntrySectionList = gcProjectEntrySectionService.selectByMainId(id);
		// 假设gcProjectEntrySectionList是您要遍历的列表
		for (GcProjectEntrySection section : gcProjectEntrySectionList) {
			// 根据section对象的SectionType属性，用于获取对应的SysCategory对象
			SysCategory sysCategory = sysCategoryService.getById(section.getSectionType());
			if (sysCategory != null) {

				section.setBdType(sysCategory.getName());
			} else {

				System.out.println("无法找到对应的SysCategory对象，sectionType: " + section.getSectionType());
			}
		}
		return Result.OK(gcProjectEntrySectionList);
	}


	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "资料项通过主表ID查询")
	 @ApiOperation(value="资料项主表ID查询", notes="资料项-通主表ID查询")
	 @GetMapping(value = "/queryGcProjectAttachmentByMainId")
	 public Result<List<GcProjectAttachment>> queryGcProjectAttachmentListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<GcProjectAttachment> gcProjectAttachmentList = gcProjectAttachmentService.selectByMainId(id);
		 return Result.OK(gcProjectAttachmentList);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param gcProjectEntry
    */
    @RequiresPermissions("gcProject:gc_project_entry:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GcProjectEntry gcProjectEntry) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<GcProjectEntry> queryWrapper = QueryGenerator.initQueryWrapper(gcProjectEntry, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<GcProjectEntry> gcProjectEntryList = gcProjectEntryService.list(queryWrapper);

      // Step.3 组装pageList
      List<GcProjectEntryPage> pageList = new ArrayList<GcProjectEntryPage>();
      for (GcProjectEntry main : gcProjectEntryList) {
          GcProjectEntryPage vo = new GcProjectEntryPage();
          BeanUtils.copyProperties(main, vo);
          List<GcProjectEntrySection> gcProjectEntrySectionList = gcProjectEntrySectionService.selectByMainId(main.getId());
          vo.setGcProjectEntrySectionList(gcProjectEntrySectionList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "项目进场列表");
      mv.addObject(NormalExcelConstants.CLASS, GcProjectEntryPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目进场数据", "导出人:"+sysUser.getRealname(), "项目进场"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("gcProject:gc_project_entry:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<GcProjectEntryPage> list = ExcelImportUtil.importExcel(file.getInputStream(), GcProjectEntryPage.class, params);
              for (GcProjectEntryPage page : list) {
                  GcProjectEntry po = new GcProjectEntry();
                  BeanUtils.copyProperties(page, po);
                  gcProjectEntryService.saveMain(po, page.getGcProjectEntrySectionList(),page.getGcProjectAttachmentList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }
	 @AutoLog(value = "项目进场-提交送审")
	 @ApiOperation(value="项目进场-提交送审", notes="项目进场-提交送审")
	 @PostMapping(value = "/submitAudit")
	 public Result<String> submitAudit(@RequestParam(name="id",required=true) String id) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 GcProjectEntry gcProjectEntryEntity = gcProjectEntryService.getById(id);
		 if(gcProjectEntryEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 gcProjectEntryEntity.setEntryStatus(StatusEnum.SUBMIT.getCode());
		 gcProjectEntryEntity.setUpdateTime(new Date());
		 gcProjectEntryEntity.setUpdateBy(sysUser.getUsername());
		 gcProjectEntryService.updateById(gcProjectEntryEntity);
		 return Result.OK("提交送审成功!");
	 }
	 @AutoLog(value = "项目进场-审核")
	 @ApiOperation(value="项目进场-审核", notes="项目进场-审核")
	 @PostMapping(value = "/audit")
	 public Result<String> audit(@RequestBody GcProjectAuditParam gcProjectAuditParam) {
		 if(gcProjectEntryService.audit(gcProjectAuditParam)){
			 return Result.OK("审核成功!");
		 }else {
			 return Result.error("审核失败!");
		 }
	 }
}
